import os
import time
import random
from string import ascii_letters
from dataclasses import dataclass

from cv2 import cv2

import numpy as np
from loguru import logger

import redis

redis_cli = redis.Redis()

@dataclass
class Counter:
    ...


def show(im):
    cv2.imshow('jpeg', im)
    cv2.waitKey(0)


@logger.catch
def getVProjection(image, im_origin):
    vProjection = np.zeros(image.shape, np.uint8)
    # 图像高与宽
    (h, w) = image.shape
    # 长度与图像宽度一致的数组
    w_ = [0] * w
    # 循环统计每一列白色像素的个数
    for y in range(h):
        print(im_origin[y, 0])

    k = 0
    nose_line = None
    for x in range(w):
        for y in range(h):
            if image[y, x] == 255:
                if k == 0:
                    k += 1
                    nose_line = im_origin[y, x]
                if (nose_line == im_origin[y, x]).all():
                    image[y, x] = 0
                else:
                    w_[x] += 1
    # 绘制垂直平投影图像
    for x in range(w):
        for y in range(h - w_[x], h):
            vProjection[y, x] = 255
    show(image)
    show(vProjection)

    return w_


#
#
# word_path = os.path.join(os.path.dirname(__file__), 'captcha_imgs')
#
# filename_list = os.listdir(word_path)
#
# for filename in filename_list:
#     # filename = filename_list[12]
#     file_path = os.path.join(word_path, filename)
#
#     im_origin = cv2.imread(file_path)
#     print(filename)
#     im_res = cv2.cvtColor(im_origin, cv2.COLOR_BGR2GRAY)  # 转灰度图
#     show(im_res)
#     ret, im_res = cv2.threshold(im_res, 180, 255, cv2.THRESH_BINARY_INV)  # 二值化
#     kernel = 1 / 16 * np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]])  # 模糊卷积核
#     im_res = cv2.filter2D(im_res, -1, kernel)  # 使用卷积核处理图片
#     r, im_res = cv2.threshold(im_res, 127, 255, cv2.THRESH_BINARY)  # 再次二值化，去除噪点
#
#     W = getVProjection(im_res, im_origin)

word_path = os.path.join(os.path.dirname(__file__), 'captcha_imgs')
filename_list = os.listdir(word_path)
for filename in filename_list:
    file_path = os.path.join(word_path, filename)
    im_origin = cv2.imread(file_path)

    im_res = cv2.cvtColor(im_origin, cv2.COLOR_BGR2GRAY)  # 转灰度图
    ret, im_res = cv2.threshold(im_res, 160
                                , 255, cv2.THRESH_BINARY_INV)  # 二值化
    kernel = 1 / 16 * np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]])  # 模糊卷积核
    im_res = cv2.filter2D(im_res, -1, kernel)  # 使用卷积核处理图片
    r, im_res = cv2.threshold(im_res, 127, 255, cv2.THRESH_BINARY)  # 再次二值化，去除噪点

    W = getVProjection(im_res, im_origin)
